<?php

namespace App\Models;

use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;

/**
 * 通用Model类
 * Class StModel
 * @package App\Models
 */
class StModel extends Model
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 通用分页查询列表方法
     * @param array $fields
     * @param array $where
     * @param array $orderBy
     * @param array $groupBy
     * @param int $pagesize
     */
    public function getList($fields = [], $where = [], $orderBy = [], $groupBy = [], $pagesize = 15)
    {
        if (!is_array($fields)) {
            $fields = explode(',', $fields);
            $fields = array_map('trim', $fields);
        }

        $query = $this->select($fields);
        $query = $this->createWhere($query, $where, $orderBy, $groupBy);

        $result = $query->paginate($pagesize);

        return $result;
    }

    /**
     * 通用查询列表方法,查询全部
     * @param array $fields
     * @param array $where
     * @param array $orderBy
     * @param array $groupBy
     * @param boolean $isArray 类型,默认是数组,对象可以传入obj
     * $return mixed 返回数组
     */
    public function getAll($fields = [], $where = [], $orderBy = [], $groupBy = [], $isArray = true, $limit = 0)
    {
        if (!is_array($fields)) {
            $fields = explode(',', $fields);
            $fields = array_map('trim', $fields);
        }

        $query = $this->select($fields);
        if($limit > 0) $query = $query->limit($limit);
        $query = $this->createWhere($query, $where, $orderBy, $groupBy);

        $result = $query->get();
        if ($isArray) {
            $result = $result->toArray();
        }

        return $result;
    }

    /**
     * 通用获取单条记录方法
     * @param array $fields
     * @param array $where
     * @param array $orderBy
     * @return array
     */
    public function getOne($fields = [], $where = [], $orderBy = [])
    {
        if (!is_array($fields)) {
            $fields = explode(',', $fields);
            $fields = array_map('trim', $fields);
        }

        $query = $this->select($fields);
        $query = $this->createWhere($query, $where, $orderBy);

        $result = $query->first();

        $result = $result ? $result->toArray() : [];

        return $result;
    }


    /**
     * 根据条件统计总数
     * @param array $where
     */
    public function countBy($where = [])
    {
        $query = $this->createWhere($this, $where);

        $result = $query->count();

        return $result;
    }

    /**
     * 根据条件更新数据
     * @param $data
     * @param array $where
     */
    public function updateBy($data, $where)
    {
        $query = $this->createWhere($this, $where);
        return $query->update($data);
    }

    /**
     * 根据条件删除数据
     * @param $data
     * @param array $where
     */
    public function deleteBy($where)
    {
        $query = $this->createWhere($this, $where);
        return $query->delete();
    }

    /**
     * 设置where条件
     * @param $query
     * @param array $where
     * @param array $orderBy
     * @param array $groupBy
     * @return mixed
     */
    public function createWhere($query, $where = [], $orderBy = [], $groupBy = [])
    {
        if (isset($where['in'])) {
            foreach ($where['in'] as $k => $v) {
                $query = $query->whereIn($k, $v);
            }
            unset($where['in']);
        }
        if (isset($where['not_in'])) {
            foreach ($where['not_in'] as $k => $v) {
                $query = $query->whereNotIn($k, $v);
            }
            unset($where['not_in']);
        }
        if (isset($where['raw'])) {
            foreach ($where['raw'] as $k => $v) {
                $query = $query->whereRaw($v);
            }
            unset($where['raw']);
        }

        if ($where) {
            foreach ($where as $k => $v) {
                $operator = '=';
                if (substr($k, -2) == ' <') {
                    $k = trim(str_replace(' <', '', $k));
                    $operator = '<';
                } elseif (substr($k, -3) == ' <=') {
                    $k = trim(str_replace(' <=', '', $k));
                    $operator = '<=';
                } elseif (substr($k, -2) == ' >') {
                    $k = trim(str_replace(' >', '', $k));
                    $operator = '>';
                } elseif (substr($k, -3) == ' >=') {
                    $k = trim(str_replace(' >=', '', $k));
                    $operator = '>=';
                } elseif (substr($k, -3) == ' !=') {
                    $k = trim(str_replace(' !=', '', $k));
                    $operator = '!=';
                } elseif (substr($k, -3) == ' <>') {
                    $k = trim(str_replace(' <>', '', $k));
                    $operator = '<>';
                } elseif (substr($k, -5) == ' like') {
                    $k = trim(str_replace(' like', '', $k));
                    $operator = 'like';
                    $v = '%' . $v . '%';
                }
                $query = $query->where($k, $operator, $v);
            }
        }

        if ($orderBy) {
            foreach ($orderBy as $k => $v) {
                $query = $query->orderBy($k, $v);
            }
        }

        if ($groupBy) {
            $query = $query->groupBy($groupBy);
        }

        return $query;
    }

    //==================== 新增 =======================

    /**
     * insert
     */
    public function add_in($data = [])
    {
        $result = $this->insert_db($data);
        //加缓存
        return $result;
    }

    public function insert_db($data = [])
    {
        try {
            $row = DB::table($this->table)->insertGetId($data);
        } catch (PDOException $e) {
            $row = 0;
        }
        return $row;
    }

    /**
     * update
     */
    public function up_table($updateParams = [], $whereParams = [])
    {
        $result = $this->update_db($updateParams, $whereParams);
        //加缓存
        return $result;
    }

    public function update_db($updateParams = [], $whereParams = [])
    {
        try {
            $row = DB::table($this->table)->where($whereParams)->update($updateParams);
        } catch (PDOException $e) {
            $row = 0;
        }
        return $row;
    }

    /**
     * 根据ids查表
     */
    public function select_by_ids($fields = [], $whereParams = [], $orderBy = [], $groupBy = [], $pagesize = 15)
    {
        $result = [];
        $ids = $this->get_ids($whereParams, $orderBy, $groupBy);
        if (empty($ids)) {
            return $result;
        }
        try {
            $row = $this->select($fields)->whereIn('id', $ids); //加缓存时，$ids 换成 $ids_out
            $row = $row->paginate($pagesize);
            $result = $row ? $row->toArray() : [];
        } catch (PDOException $e) {
            $result = [];
        }
        return $result;
    }

    //查出ids
    public function get_ids($whereParams = [], $orderBy = [], $groupBy = [])
    {
        try {
            $selectArr = [$this->primaryKey];
            $row = $this->select($selectArr);
            $row = $this->createWhere($row, $whereParams, $orderBy, $groupBy)->get();
            $row = $row->toArray();
            $ids = array();
            $ids = array_column($row, $this->primaryKey); // 函数array_column()的版本要求：PHP 5.5+
        } catch (PDOException $e) {
            $ids = [];
        }
        return $ids;
    }
}
